#coding=utf-8

import cv2  
import numpy as np  
import matplotlib.pyplot as plt

  
def salt(img, n):  
    for k in xrange(n):  
        i = int(np.random.random() * img.shape[1]);  
        j = int(np.random.random() * img.shape[0]);  
        
        #Black
        if img.ndim == 2:   
            img[j,i] = 255  
        
        #RBG
        elif img.ndim == 3:   
            img[j,i,0]= 255  
            img[j,i,1]= 255  
            img[j,i,2]= 255  
    return img  

def brgSplit(img):
    b=cv2.split(img)[0]
    g=cv2.split(img)[1]
    r=cv2.split(img)[2]
    
    return b,g,r


def calcAndDrawHist(image, color):  
    hist= cv2.calcHist([image], [0], None, [256], [0.0,255.0])  
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)  
    histImg = np.zeros([256,256,3], np.uint8)  
    hpt = int(0.9* 256);  
      
    for h in range(256):  
        intensity = int(hist[h]*hpt/maxVal)  
        cv2.line(histImg,(h,256), (h,256-intensity), color)  
          
    return histImg; 



def globalEqualizeHist(img):
    equ = cv2.equalizeHist(img) 
    return equ

def localEqualizeHist(img):
    clache=cv2.createCLAHE(clipLimit=2,tileGridSize=(5,5))
    cl1=clache.apply(img)

    return cl1



def calcHist(img):

#     image输入图像，传入时应该用中括号[]括起来
#     channels:：传入图像的通道，如果是灰度图像，那就不用说了，只有一个通道，值为0，如果是彩色图像（有3个通道），那么值为0,1,2,中选择一个，对应着BGR各个通道。这个值也得用[]传入。
#     mask：掩膜图像。如果统计整幅图，那么为none。主要是如果要统计部分图的直方图，就得构造相应的炎掩膜来计算。
#     histSize：灰度级的个数，需要中括号，比如[256]
#     ranges:像素值的范围，通常[0,256]，有的图像如果不是0-256，比如说你来回各种变换导致像素值负值、很大，则需要调整后才可以。
    hist_cv = cv2.calcHist([img],[0],None,[256],[0,256])  
    return hist_cv



if __name__ == '__main__':
    img=cv2.imread("..\\img\\5.jpg",0)
    hist_cv=calcHist(img)
    g_equ=globalEqualizeHist(img)
    hist_1=calcHist(g_equ)
    cl1=localEqualizeHist(img)
    hist_2=calcHist(cl1)
    
#     cv2.imshow("ori",img)
    print type(hist_cv)
    
    plt.subplot(321),plt.imshow(img,'gray')
    plt.subplot(322),plt.plot(hist_cv)
    plt.subplot(323),plt.imshow(g_equ,'gray')
    plt.subplot(324),plt.plot(hist_1)
    plt.subplot(325),plt.imshow(cl1,'gray')
    plt.subplot(326),plt.plot(hist_2)
    plt.show()
#     cv2.imshow('gray',img)
#     cv2.waitKey(0)
#     cv2.destroyAllWindows()

       
    
    

